package com.qianke.core.service.impl;

import com.qianke.common.RedisUtils;
import com.qianke.core.mapper.AdminMenuMapper;
import com.qianke.core.service.AdminMenuService;
import com.qianke.domain.Constants;
import com.qianke.domain.dto.AdminMenuDto;
import com.qianke.domain.dto.LoginUserDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AdminMenuServiceImpl implements AdminMenuService {

    @Resource
    private AdminMenuMapper adminMenuMapper;

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean checkPermission(String requestUri, LoginUserDto loginUserDto) {
        boolean flag = false;
        if (StringUtils.isNotEmpty(loginUserDto.getPermissions())) {
            if (queryAdminMenuList(loginUserDto.getRoleCode(), loginUserDto.getMenuIds()).contains(requestUri)) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public String queryAdminMenuList(String roleCode, String menuIdStr) {
        RedisTemplate redisTemplateDB = RedisUtils.setConnectionFactoryDB(this.redisTemplate, 1);
        String urls = (String) redisTemplateDB.opsForValue().get(roleCode);
        if (StringUtils.isEmpty(urls) && StringUtils.isNotEmpty(menuIdStr)) {
            int[] menuIds = Arrays.stream(menuIdStr.split(",")).mapToInt(Integer::parseInt).toArray();
            List<AdminMenuDto> ruleList = adminMenuMapper.queryAllAdminRuleByIdList(menuIds);
            StringBuilder stringBuilder = new StringBuilder();
            for (AdminMenuDto adminRuleDto : ruleList) {
                stringBuilder.append(adminRuleDto.getUrl());
            }
            urls = stringBuilder.toString();
            //更新redis
            updateRoleUrlsRedis(roleCode, urls);
        }
        return urls;
    }

    //更新redis中角色对应的菜单url
    private void updateRoleUrlsRedis(String roleCode, String urls) {
        RedisTemplate redisTemplateDB = RedisUtils.setConnectionFactoryDB(this.redisTemplate, 1);
        redisTemplateDB.opsForValue().set(roleCode, urls, Constants.ROLE_TIMEOUT, TimeUnit.HOURS);
    }


}
